package com.socket.nio.nio.sticky.fixedlength;

import cn.hutool.core.util.StrUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author Hexudong
 * @date 2025/5/4
 */
public class FixedLengthServerHandler extends SimpleChannelInboundHandler<String> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) {
    System.out.println("Server received: [" + msg + "]");
    // 使用hutool工具类将消息长度不足10位的以'-'在右侧补充
    String response = StrUtil.padAfter(msg, 10, "-");
    ctx.writeAndFlush(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
  }
}
